﻿package net.area80.file {
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	
	/**
	 * ImageBrowser
	 * @author Wissarut Pimanmassuriya
	 */
	public class ImageBrowser extends AbstractImageBrowser {
		
		private var fileRef:FileReference;
		public const PARH_PROGRAM:String = "http://pepsifootvolley.adapterproject.com/";
		//public const PARH_PROGRAM:String = "http://nokiahunt.adapterproject.com/";
		public const UPLOAD_PROCESS:String = PARH_PROGRAM + "upload.axd";
		public const UPLOAD_GET_PICNAME:String = PARH_PROGRAM + "uploadname.aspx";
		//public const PIC_PATH:String = PARH_PROGRAM;
		public const PIC_PATH:String = PARH_PROGRAM + "image_face/";
		public var state:String = "upload";
		
		private var fileName:String;
		private const fileNameChars:String = "0123456789abcdefghijklmnopqrstuvwxyz";
		
				
		public function ImageBrowser (type:/*FileFilter*/Array, size:int = 0, smoothing:Boolean = false):void {
				super(type, size, smoothing);
		}
		
		private function getFileName ():String {
			var str:String = String(new Date().getTime());
			for (var i:uint = 0; i < 5; i++) {
				str = str + fileNameChars.charAt(Math.round(Math.random() * (fileNameChars.length - 1)));
			}
			return str+".jpg";
		}
		
		override public function browse ():void {
			state = "upload";

			if (!type || type.length == 0) dispatchErrorEvent("File type doesn't set yet");
			fileRef = new FileReference();
					
			fileRef.addEventListener(Event.SELECT, fileSelect);
			fileRef.addEventListener(Event.OPEN, openHandler);
			fileRef.addEventListener(Event.COMPLETE, completeHandler);
			fileRef.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			
			fileRef.browse(type);

		}

		private function openHandler(e:Event):void {
			
		}
		
		private function  downloadName():void {
				trace("request from : " + UPLOAD_GET_PICNAME);
				
				var request:URLRequest = new URLRequest();
				request.url = UPLOAD_GET_PICNAME;
				request.method = URLRequestMethod.POST;
				var loader:URLLoader = new URLLoader();
				loader.dataFormat = URLLoaderDataFormat.TEXT;
				loader.addEventListener(Event.COMPLETE, getPathFileCompleted);
				loader.load(request);

			
		}
		private function getPathFileCompleted (e:Event):void {
					var loader:URLLoader = URLLoader(e.target);
					var loaderReturn:URLVariables = new URLVariables(loader.data);
					try {
						trace("\t----- Recived FileName, downoading the file -----------------------------------");
						trace(PIC_PATH + loaderReturn.pic_name);
						state = "download";
						loadFile(PIC_PATH + loaderReturn.pic_name);
						
					} catch (error:Error) {
						trace("Unable to load URL");
						dispatchErrorEvent("Unable to load URL "+ PIC_PATH + loaderReturn.pic_name);
					}
		}
		private function completeHandler(e:Event):void {
			e.target.removeEventListener(Event.COMPLETE, completeHandler);
			//downloadName();
			doDownloadFile();
			//trace(e);
		}
		private function doDownloadFile ():void {
				trace("\t----- Downoading the File -----------------------------------");
				trace(PIC_PATH + fileName);
				state = "download";
				loadFile(PIC_PATH + fileName);
		}

		
		private function ioErrorHandler(e:IOErrorEvent):void {
			//trace(e);
		}
		
		protected override function progressHandler(e:ProgressEvent):void {
			var ev:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS);
			if (state == "upload") {
				ev.bytesTotal = e.bytesTotal;
				ev.bytesLoaded = e.bytesLoaded*0.5;
				dispatchEvent(ev);
			} else if (state == "download") {
				ev.bytesTotal = e.bytesTotal;
				ev.bytesLoaded = (e.bytesTotal * 0.5) + (e.bytesLoaded * 0.5);	
				dispatchEvent(ev);
			}
		}
		
		private function securityErrorHandler(e:Event):void {
			//trace(e);
		}
		
		private function fileSelect(e:Event):void {
			//trace(e);
			state = "upload";
			
			if (fileRef.size > 500 * 1024) {
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,"ไฟล์ภาพต้องมีขนาดไม่เกิน 500kb"));
			} else {
				fileName = getFileName();
				dispatchEvent(new Event(Event.SELECT));
				fileRef.upload(new URLRequest(UPLOAD_PROCESS + "?filename=" + fileName));
			}
		}


		
	}
	
}